var player = null;
var totalTimeWatched = 0;
var playing = false;
var recordingSampleInterval = 5000; //5 seconds
var lastTimeCalled = null;
function sendTotalTimeWatchedToServer() {
	if(totalTimeWatched > 0) {
		jQuery.ajax({
			type: "POST",
			async: false,
			url: "saveTotalTimeWatched.php",
			data: "totalTimeWatched="+totalTimeWatched+"&videoName="+jQuery('#videoName').val()
		});
	}
}
jQuery(window).unload(function() {
	sendTotalTimeWatchedToServer();
});
var States = {
		playingNotStarted : -1,
		playingEnded : 0,
		playingPlay : 1,
		playingPaused : 2,
		playingBuffering : 3,
		playingPeriodicEvent : -2
}
function onYouTubePlayerReady(playerId) {
	player = jQuery('#idPlayer')[0];
	if (player != null) {
		bindEvent();
	}
	lastTimeCalled = new Date();
}
function bindEvent() {
	player.addEventListener("onStateChange", "playerStateChanged");
	setInterval(function() {
		playerStateChanged(States.playingPeriodicEvent);
	}, 5000);
}
function playerStateChanged(state) {
	if (state == States.playingNotStarted) {
		playing = false;
	} else if (state == States.playingEnded) {
		playing = false;
		sendTotalTimeWatchedToServer();
		totalTimeWatched = 0;
	} else if (state == States.playingPlay) {
		playing = true;
	} else if (state == States.playingPaused) {
		playing = false;
	} else if (state == States.playingBuffering) {
		playing = false;
	} else if (state == States.playingPeriodicEvent) {
		if (playing) {
			totalTimeWatched+= ((new Date()) - lastTimeCalled) / 1000.0;
		}
		lastTimeCalled = new Date();
	}
}